<template>
  <div v-if="reportDataList && reportDataList.length > 0">
    <ContentWrap v-if="showSearch == 1 && !props.reportId">
      <el-form label-width="150px" ref="formRef" :model="searchValue" class="flex flex-wrap">
        <el-col :span="6" v-if="templateList && templateList.length > 0">
          <el-form-item label="数据保护标准">
            <el-select v-model="searchValue.template" clearable placeholder="请选择数据标准">
              <el-option
                v-for="(template, templateIndex) in templateList"
                :key="templateIndex"
                :label="template.dataStandardName"
                :value="template.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="分类">
            <el-cascader
              style="width: 100%"
              v-model="searchValue.classification"
              placeholder="请选择分类"
              :props="classificationCascaderProps"
              :options="classificationList"
              filterable
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="分类展示级别">
            <el-select v-model="searchValue.showClassGrade" clearable placeholder="请选择展示级别">
              <el-option
                v-for="(grade, gradeIndex) in gradeList"
                :key="gradeIndex"
                :label="grade.label"
                :value="grade.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="等级">
            <el-select v-model="searchValue.level" clearable placeholder="请选择等级">
              <el-option
                v-for="(level, levelIndex) in levelList"
                :key="levelIndex"
                :label="level.levelName"
                :value="level.levelCode"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="deptList && deptList.length > 0">
          <el-form-item label="所属组织机构">
            <el-cascader
              style="width: 100%"
              v-model="searchValue.dept"
              clearable
              placeholder="请选择归属机构"
              :options="deptList"
              :props="cascaderProps"
              filterable
              :filter-method="sysFilterMethod"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="deptList && deptList.length > 0">
          <el-form-item label="组织机构展示级别">
            <el-select v-model="searchValue.showDeptGrade" clearable placeholder="请选择展示级别">
              <el-option
                v-for="(grade, gradeIndex) in gradeList"
                :key="gradeIndex"
                :label="grade.label"
                :value="grade.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="systemList && systemList.length > 0">
          <el-form-item label="所属应用系统">
            <el-cascader
              style="width: 100%"
              v-model="searchValue.sys"
              placeholder="请选择归属系统"
              :props="systemCascaderProps"
              :options="systemList"
              filterable
              :filter-method="sysFilterMethod"
              clearable
          /></el-form-item>
        </el-col>
        <el-col :span="6" v-if="systemList && systemList.length > 0">
          <el-form-item label="应用系统展示级别">
            <el-select v-model="searchValue.showSysGrade" clearable placeholder="请选择展示级别">
              <el-option
                v-for="(grade, gradeIndex) in gradeList"
                :key="gradeIndex"
                :label="grade.label"
                :value="grade.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="展示数量">
            <ns-input type="number" v-model="searchValue.number" placeholder="默认展示数量为5" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="统计期间">
            <el-select v-model="searchValue.defaultTime" clearable placeholder="请选择统计期间">
              <el-option label="所有" :value="0" />
              <el-option label="本日" :value="1" />
              <el-option label="本周" :value="2" />
              <el-option label="本月" :value="3" />
              <el-option label="本年" :value="4" />
              <el-option label="自定义期间" :value="5" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="searchValue.defaultTime === 5">
          <el-form-item label="日期范围">
            <el-date-picker
              v-model="searchValue.timeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="timeRangeChange"
            />
          </el-form-item>
        </el-col>
      </el-form>
      <el-row>
        <el-col :span="24" class="text-right">
          <el-button @click="searchReset" plain>重置</el-button>
          <el-button @click="getReportData" plain>搜索</el-button>
        </el-col>
      </el-row>
    </ContentWrap>
    <ContentWrap>
      <div class="data-container flex flex-justify-between" ref="dataWrapRef">
        <el-card shadow="never" style="width: 100%">
          <div class="text-center font-size-24px">
            {{ preData.name }}
          </div>
          <div id="draggable-menu">
            <div v-for="(menu, menuIndex) in menuList" :key="menuIndex" class="mb-22px">
              <div v-if="menu.show">
                <SubTitle :title="menu.dataObjectName" />
                <div :id="`chart-box${menuIndex}`">
                  <div v-for="(viewItem, viewIndex) in menu.view" :key="viewIndex" class="mb-12px">
                    <div v-if="viewItem.chartsType === 'Table'" class="w-100%">
                      <el-table
                        :data="menu.tableData"
                        style="width: 100%"
                        :span-method="SpanMethodList[menuIndex].SpanMethod"
                      >
                        <el-table-column label="" width="150">
                          <!-- <template #default="scope">
                            <div> {{ scope.$index === 0 ? '合计' : menu.dataObjectName }} </div>
                          </template> -->
                          <template #default>
                            <div> {{ menu.dataObjectName }} </div>
                          </template>
                        </el-table-column>
                        <el-table-column prop="dataObjectName" label="" width="150" />
                        <el-table-column label="" width="150">
                          <template #default="scope">
                            <div v-if="scope.$index === 0">{{ getSum(scope, menu) }}</div>
                            <div v-else-if="scope.$index !== 0 && menu.spanRowNum === 3">
                              <!-- 就没有对统计的的信息进行展示处理了 -->
                              <!-- <div v-if="scope.$index % 4 === 1"> 数据源 </div> -->
                              <div v-if="scope.$index % 3 === 1"> 数据表 </div>
                              <div v-if="scope.$index % 3 === 2"> 数据表字段 </div>
                              <div v-if="scope.$index % 3 === 0"> 文件资产 </div>
                            </div>
                            <div v-else-if="scope.$index !== 0 && menu.spanRowNum === 2">
                              <!-- <div v-if="scope.$index % 2 === 1"> 数据源 </div> -->
                              <div v-if="scope.$index % 2 === 1"> 数据表</div>
                              <div v-if="scope.$index % 2 === 0"> 数据表字段 </div>
                            </div>
                            <div v-else-if="scope.$index !== 0 && menu.spanRowNum === 1">
                              <div> 文件资产 </div>
                            </div>
                          </template>
                        </el-table-column>

                        <el-table-column
                          :label="tableColumn"
                          v-for="(tableColumn, tableColumnIndex) in viewItem.others"
                          :key="tableColumnIndex"
                        >
                          <el-table-column
                            v-for="(dataItem, dataIndex) in menu[
                              `${dataTypeMap.get(tableColumn)}List`
                            ]"
                            :key="dataIndex"
                            :label="dataItem.name"
                            :prop="`${dataTypeMap.get(tableColumn)}${dataItem.name}`"
                          />
                          <!-- :prop="`${dataTypeMap.get(tableColumn)}${dataIndex + 1}`" -->
                        </el-table-column>
                      </el-table>
                    </div>
                    <div v-if="viewItem.chartsType === 'Pie'" class="w-100%">
                      <div
                        v-for="(reportDataItem, reportDataIndex) in menu[
                          `${dataTypeMap.get(menu.dataObjectName)}List`
                        ]"
                        :key="reportDataIndex"
                        class="flex justify-evenly"
                      >
                        <div
                          v-for="(reportItem, reportIndex) in reportDataList[menuIndex]?.pie[
                            reportDataItem.name
                          ]"
                          :key="reportIndex"
                          class="w-25%"
                          v-show="
                            ((reportIndex === 'file' &&
                              viewItem.dataType.find((item) => item === '非结构化资产')) ||
                              (reportIndex !== 'file' &&
                                viewItem.dataType.find((item) => item === '结构化资产'))) &&
                            reportIndex !== 'source'
                          "
                        >
                          <div v-for="(pieItem, pieIndex) in reportItem" :key="pieIndex">
                            <div
                              v-if="
                                (pieIndex === 'deptMap' ||
                                  pieIndex === 'sysMap' ||
                                  pieIndex === 'templateMap') &&
                                pieItem
                              "
                              class="p-20px"
                            >
                              <Echart
                                :height="300"
                                :options="reportItem.pieDeptData"
                                v-if="
                                  pieIndex === 'deptMap' &&
                                  viewItem.others.find(
                                    (item) =>
                                      item === '所属组织机构' ||
                                      item === 'Affiliated Organizational Structure'
                                  )
                                "
                              />
                              <Echart
                                :height="300"
                                :options="reportItem.pieSysData"
                                v-else-if="
                                  pieIndex === 'sysMap' &&
                                  viewItem.others.find(
                                    (item) =>
                                      item === '所属应用系统' ||
                                      item === 'Associated Application System'
                                  )
                                "
                              />
                              <Echart
                                :height="300"
                                :options="reportItem.pieTemplateData"
                                v-else-if="
                                  pieIndex === 'templateMap' &&
                                  viewItem.others.find(
                                    (item) =>
                                      item === '数据保护标准' ||
                                      item === 'Data Protection Standards'
                                  )
                                "
                              />
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div v-if="viewItem.chartsType === 'Bar'">
                      <div
                        v-for="(reportDataItem, reportDataIndex) in menu[
                          `${dataTypeMap.get(menu.dataObjectName)}List`
                        ]"
                        :key="reportDataIndex"
                        class="flex justify-evenly"
                      >
                        <div
                          v-for="(reportItem, reportIndex) in reportDataList[menuIndex]?.pie[
                            reportDataItem.name
                          ]"
                          :key="reportIndex"
                          class="w-25%"
                          v-show="
                            ((reportIndex === 'file' &&
                              viewItem.dataType.find((item) => item === '非结构化资产')) ||
                              (reportIndex !== 'file' &&
                                viewItem.dataType.find((item) => item === '结构化资产'))) &&
                            reportIndex !== 'source'
                          "
                        >
                          <div v-for="(pieItem, pieIndex) in reportItem" :key="pieIndex">
                            <div
                              v-if="
                                (pieIndex === 'deptMap' ||
                                  pieIndex === 'sysMap' ||
                                  pieIndex === 'templateMap') &&
                                pieItem
                              "
                              class="mt-20px"
                            >
                              <Echart
                                :height="300"
                                :options="reportItem.barDeptData"
                                v-if="
                                  pieIndex === 'deptMap' &&
                                  viewItem.others.find(
                                    (item) =>
                                      item === '所属组织机构' ||
                                      item === 'Affiliated Organizational Structure'
                                  )
                                "
                              />
                              <Echart
                                :height="300"
                                :options="reportItem.barSysData"
                                v-else-if="
                                  pieIndex === 'sysMap' &&
                                  viewItem.others.find(
                                    (item) =>
                                      item === '所属应用系统' ||
                                      item === 'Associated Application System'
                                  )
                                "
                              />
                              <Echart
                                :height="300"
                                :options="reportItem.barTemplateData"
                                v-else-if="
                                  pieIndex === 'templateMap' &&
                                  viewItem.others.find(
                                    (item) =>
                                      item === '数据保护标准' ||
                                      item === 'Data Protection Standards'
                                  )
                                "
                              />
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div v-if="viewItem.chartsType === 'Line'">
                      <div
                        v-for="(reportDataItem, reportDataIndex) in menu[
                          `${dataTypeMap.get(menu.dataObjectName)}List`
                        ]"
                        :key="reportDataIndex"
                        class="flex justify-evenly"
                      >
                        <div
                          v-for="(reportItem, reportIndex) in reportDataList[menuIndex]?.list[
                            reportDataItem.name
                          ]"
                          :key="reportIndex"
                          class="w-25%"
                          v-show="
                            ((reportIndex === 'file' &&
                              viewItem.dataType.find((item) => item === '非结构化资产')) ||
                              (reportIndex !== 'file' &&
                                viewItem.dataType.find((item) => item === '结构化资产'))) &&
                            reportIndex !== 'source'
                          "
                        >
                          <div v-for="(pieItem, pieIndex) in reportItem" :key="pieIndex">
                            <div
                              v-if="
                                (pieIndex === 'deptMap' ||
                                  pieIndex === 'sysMap' ||
                                  pieIndex === 'templateMap') &&
                                pieItem
                              "
                              class="mt-20px"
                            >
                              <Echart
                                :height="300"
                                :options="reportItem.lineDeptData"
                                v-if="
                                  pieIndex === 'deptMap' &&
                                  viewItem.others.find(
                                    (item) =>
                                      item === '所属组织机构' ||
                                      item === 'Affiliated Organizational Structure'
                                  )
                                "
                              />
                              <Echart
                                :height="300"
                                :options="reportItem.lineSysData"
                                v-else-if="
                                  pieIndex === 'sysMap' &&
                                  viewItem.others.find(
                                    (item) =>
                                      item === '所属应用系统' ||
                                      item === 'Associated Application System'
                                  )
                                "
                              />
                              <Echart
                                :height="300"
                                :options="reportItem.lineTemplateData"
                                v-else-if="
                                  pieIndex === 'templateMap' &&
                                  viewItem.others.find(
                                    (item) =>
                                      item === '数据保护标准' ||
                                      item === 'Data Protection Standards'
                                  )
                                "
                              />
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </ContentWrap>
  </div>
  <!-- <div v-else class="text-center"> 暂无数据 </div> -->
</template>

<script lang="ts" setup>
import SubTitle from '@/components/SubTitle/index.vue'
import * as reportManageApi from '@/api/report/reportManage/index'
import * as reportTempApi from '@/api/report/reportTemp/index'
import { EChartsOption } from 'echarts'
import { barOptions, lineOptions, pieOptions } from '@/views/report/display/echarts-data'
import { dataStandardsPage } from '@/api/dataStandards/standards/index'
import { dataClassificationTree } from '@/api/dataStandards/classification/index'
import { levelPage } from '@/api/strategyManage/level/index'
import { getSimpleDeptList } from '@/api/system/dept'
import { getSimpleSystemList } from '@/api/asset/taskManage'
import { handleTree } from '@/utils/tree'
import { sysFilterMethod } from '@/utils/selectFilter'
import { ElLoading } from 'element-plus'
import dayjs from 'dayjs'

const route = useRoute()
const routeName = ref(route.name)

const props = defineProps({
  reportId: String
})
const preData = ref(route.query)
const dataWrapRef = ref()
const showSearch = ref(0)
const defaultQuery = ref({
  template: undefined,
  classification: undefined,
  showClassGrade: undefined,
  level: undefined,
  dept: undefined,
  showDeptGrade: undefined,
  sys: undefined,
  showSysGrade: undefined,
  defaultTime: undefined,
  timeRange: undefined,
  number: undefined
})
const searchValue = ref({
  template: undefined,
  classification: undefined,
  showClassGrade: undefined,
  level: undefined,
  dept: undefined,
  showDeptGrade: undefined,
  sys: undefined,
  showSysGrade: undefined,
  defaultTime: undefined,
  timeRange: undefined,
  number: undefined
})
const classificationCascaderProps = ref({
  checkStrictly: true,
  label: 'text',
  value: 'id',
  children: 'children',
  emitPath: false
})
const cascaderProps = ref({
  checkStrictly: true,
  label: 'name',
  value: 'id',
  children: 'children',
  emitPath: false
})
const systemCascaderProps = {
  checkStrictly: true,
  label: 'value',
  value: 'id',
  children: 'children',
  emitPath: false
}
const gradeList = [
  {
    label: '一级',
    value: '1'
  },
  {
    label: '二级',
    value: '2'
  },
  {
    label: '三级',
    value: '3'
  },
    {
    label: '四级',
    value: '4'
  },
    {
    label: '五级',
    value: '5'
  },
    {
    label: '六级',
    value: '6'
  },
    {
    label: '七级',
    value: '7'
  },
    {
    label: '八级',
    value: '8'
  },
    {
    label: '九级',
    value: '9'
  },
   {
    label: '十级',
    value: '10'
  }
]
// 排版
const menuList = ref([
  {
    show: true,
    dataObject: 'StandardStatistics',
    dataObjectName: '数据保护标准',
    spanRowNum: 3, //表格行单位，由dataType: ['结构化资产', '非结构化资产']控制
    tableData: [
      {
        dataObjectName: '',
        total: ''
      }
    ], //表格数据
    templateList: [], //标准列表
    deptList: [], //部门列表
    sysList: [], //系统列表
    view: [
      {
        chartsType: 'Table',
        dataType: ['结构化资产', '非结构化资产'],
        others: ['所属组织机构', '所属应用系统']
      },
      {
        chartsType: 'Table',
        dataType: ['结构化资产'],
        others: ['所属组织机构', '所属应用系统']
      }
    ]
  }
])

// 数据
const reportDataList = ref([])

const dataTypeMap = new Map([
  [location.href.indexOf('/en/') >= 0 ? 'Data Protection Standards' : '数据保护标准', 'template'],
  [location.href.indexOf('/en/') >= 0 ? 'Affiliated Organizational Structure' : '所属组织机构','dept'],
  [location.href.indexOf('/en/') >= 0 ? 'Associated Application System' : '所属应用系统', 'sys']
])
const dataTypeList = new Map([
  ['source', '数据源'],
  ['table', '数据表字段'],
  ['column', '数据表'],
  ['file', '文件资产']
])

const SpanMethodList = [
  {
    SpanMethod: ({ row, column, rowIndex, columnIndex }) => {
      // 第一列合并单元格（标题：数据保护标准）
      if (columnIndex === 0) {
        if (rowIndex % menuList.value[0]?.tableData.length === 0) {
          return {
            rowspan: menuList.value[0]?.tableData.length,
            colspan: 1
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      } else if (columnIndex === 1) {
        // 第二列合并单元格（各个数据保护标准（四个为一组））
        if (rowIndex === 0) {
          return {
            rowspan: 1,
            colspan: 1
          }
        } else if ((rowIndex - 1) % menuList.value[0]?.spanRowNum === 0) {
          return {
            rowspan: menuList.value[0]?.spanRowNum,
            colspan: 1
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      }
    }
  },
  {
    SpanMethod: ({ row, column, rowIndex, columnIndex }) => {
      // 第一列合并单元格（标题：数据保护标准）
      if (columnIndex === 0) {
        if (rowIndex % menuList.value[1]?.tableData.length === 0) {
          return {
            rowspan: menuList.value[1]?.tableData.length,
            colspan: 1
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      } else if (columnIndex === 1) {
        // 第二列合并单元格（各个数据保护标准（四个为一组））
        if (rowIndex === 0) {
          return {
            rowspan: 1,
            colspan: 1
          }
        } else if ((rowIndex - 1) % menuList.value[1]?.spanRowNum === 0) {
          return {
            rowspan: menuList.value[1]?.spanRowNum,
            colspan: 1
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      }
    }
  },
  {
    SpanMethod: ({ row, column, rowIndex, columnIndex }) => {
      // 第一列合并单元格（标题：数据保护标准）
      if (columnIndex === 0) {
        if (rowIndex % menuList.value[2]?.tableData.length === 0) {
          return {
            rowspan: menuList.value[2]?.tableData.length,
            colspan: 1
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      } else if (columnIndex === 1) {
        // 第二列合并单元格（各个数据保护标准（四个为一组））
        if (rowIndex === 0) {
          return {
            rowspan: 1,
            colspan: 1
          }
        } else if ((rowIndex - 1) % menuList.value[2]?.spanRowNum === 0) {
          return {
            rowspan: menuList.value[2]?.spanRowNum,
            colspan: 1
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      }
    }
  }
]

const formRef = ref()
const searchReset = () => {
  // formRef.value.resetFields()
  searchValue.value = {
    template: undefined,
    classification: undefined,
    showClassGrade: undefined,
    level: undefined,
    dept: undefined,
    showDeptGrade: undefined,
    sys: undefined,
    showSysGrade: undefined,
    defaultTime: undefined,
    timeRange: undefined,
    number: undefined
  }
  searchValue.value.defaultTime = defaultQuery.value.defaultTime
  getReportData()
}

function timeRangeChange(e) {
  searchValue.value.startTime = dayjs(e[0]).format('YYYY-MM-DD')
  searchValue.value.endTime = dayjs(e[1]).format('YYYY-MM-DD')
}

const emit = defineEmits(['homeWorkBench', 'refreshWork'])

// 获取数据和模版
const getReportData = async () => {
  emit('refreshWork', searchValue.value.defaultTime, searchValue.value.timeRange)
  const loading = ElLoading.service({
    target: dataWrapRef.value,
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  try {
    let data
    if (route.name === 'display' || route.query.id || props.reportId) {
      data = await reportManageApi.reportManageShow({
        id: route.query.id || props.reportId,
        ...searchValue.value,
        language: location.href.indexOf('/en/') >= 0 ? 'en' : ''
      })
    } else {
      data = await reportManageApi.reportManageHomeReport({
        ...searchValue.value,
        language: location.href.indexOf('/en/') >= 0 ? 'en' : ''
      })
    }

    console.log('hch 表格data', data)
    // menuList.value = JSON.parse(data.reportManage?.composing)
    if (!data) return
    // 模版
    showSearch.value = data.reportManage?.tempVO?.reportSearch
    emit('homeWorkBench', data.reportManage?.tempVO?.showWorkbench)
    menuList.value = JSON.parse(data.reportManage?.composing)
    const composing = JSON.parse(data.reportManage?.composing)
    menuList.value = composing.map((item) => {
      // 获取当前表格的数据类型：结构化与非结构化
      const dataType = item.view.find((item) => item.chartsType == 'Table')?.dataType
      let spanRowNum
      if (dataType?.length == 2) {
        spanRowNum = 3
      } else if (dataType?.some((item) => item == '结构化资产')) {
        spanRowNum = 2
      } else if (dataType?.some((item) => item == '非结构化资产')) {
        spanRowNum = 1
      }
      return {
        ...item,
        spanRowNum
      }
    })
    // 数据
    reportDataList.value = data.reportData
    const reportData = data.reportData
    reportData.map((dataItem, dataIndex) => {
      // TODO：先注释掉 ,这个是控制对应的数据属性的处理,
      if (menuList.value[dataIndex].show) { 
        menuList.value[dataIndex].tableData = []
        menuList.value[dataIndex].templateList = dataItem.templateList
        menuList.value[dataIndex].deptList = dataItem.deptList
        menuList.value[dataIndex].sysList = dataItem.sysList
        // 表格数据处理
        const deptTableData = arrayToObject(dataItem.deptList, 'dept')
        const sysTableData = arrayToObject(dataItem.sysList, 'sys')
        const templateTableData = arrayToObject(dataItem.templateList, 'template')
        // 第一行数据
        if (dataItem.mainStaic == 'templateList') {
          menuList.value[dataIndex].tableData[0] = {
            ...deptTableData,
            ...sysTableData,
            total: '合计'
          }
        } else if (dataItem.mainStaic == 'deptList') {
          menuList.value[dataIndex].tableData[0] = {
            ...templateTableData,
            ...sysTableData,
            total: '合计'
          }
        } else if (dataItem.mainStaic == 'sysList') {
          menuList.value[dataIndex].tableData[0] = {
            ...templateTableData,
            ...deptTableData,
            total: '合计'
          }
        }
        // 表格后面数据处理（先创建处理数组长度）
        const tableUnitRow = menuList.value[dataIndex].spanRowNum
        dataItem[dataItem.mainStaic].forEach((item) => {
          for (let i = 0; i < tableUnitRow; i++) {
            menuList.value[dataIndex].tableData.push({ dataObjectName: item.name })
          }
        })
        // (再将数据一点点放进数组中)
        for (const dataObjectName in dataItem.list) {
          // dataObjectName (数据标准名称)
          for (const tableRowName in dataItem.list[dataObjectName]) {
            // tableRowName 数据类型名称：source，table，column，file
            const findIndex = menuList.value[dataIndex].tableData.findIndex(
              (item) => item.dataObjectName === dataObjectName
            )
            const deptData = {}
            const sysData = {}
            const templateData = {}
            // 数据在表格数据中的位置
            let addIndexNum = 0
            if (tableUnitRow === 3) {
              const dataTypeMap = new Map([
                ['column', 1],
                ['file', 2],
                // ['source', 0],
                ['table', 0]
              ])
              addIndexNum = dataTypeMap.has(tableRowName) ? dataTypeMap.get(tableRowName) : -1
            } else if (tableUnitRow === 2) {
              const dataTypeMap = new Map([
                ['column', 1],
                // ['source', 0],
                ['table', 0]
              ])
              addIndexNum = dataTypeMap.has(tableRowName) ? dataTypeMap.get(tableRowName) : -1
            } else if (tableUnitRow === 1) {
              const dataTypeMap = new Map([['file', 0]])
              addIndexNum = dataTypeMap.has(tableRowName) ? dataTypeMap.get(tableRowName) : -1
            }
            for (const objTypeName in dataItem.list[dataObjectName][tableRowName]) {
              // objTypeName deptMap，sysMap，templateMap
              // 将接收到的数据+前缀，防止相同名字导致的问题
              if (
                objTypeName === 'deptMap' &&
                dataItem.list[dataObjectName][tableRowName].deptMap
              ) {
                Object.keys(dataItem.list[dataObjectName][tableRowName].deptMap).forEach((key) => {
                  deptData[`dept${key}`] = dataItem.list[dataObjectName][tableRowName].deptMap[key]
                })
              } else if (
                objTypeName === 'sysMap' &&
                dataItem.list[dataObjectName][tableRowName].sysMap
              ) {
                Object.keys(dataItem.list[dataObjectName][tableRowName].sysMap).forEach((key) => {
                  sysData[`sys${key}`] = dataItem.list[dataObjectName][tableRowName].sysMap[key]
                })
              } else if (
                objTypeName === 'templateMap' &&
                dataItem.list[dataObjectName][tableRowName].templateMap
              ) {
                Object.keys(dataItem.list[dataObjectName][tableRowName].templateMap).forEach(
                  (key) => {
                    templateData[`template${key}`] =
                      dataItem.list[dataObjectName][tableRowName].templateMap[key]
                  }
                )
              }
            }
            if (findIndex !== -1 && addIndexNum !== -1) {
              menuList.value[dataIndex].tableData[findIndex + addIndexNum] = {
                ...menuList.value[dataIndex].tableData[findIndex + addIndexNum],
                total: dataItem.list[dataObjectName][tableRowName].total,
                ...deptData,
                ...sysData,
                ...templateData
              }
            }
          }
        }
        //Pie数据和Bar数据
        for (const dataObjectName in dataItem.pie) {
          // dataObjectName 标准名称
          for (const dataTypeName in dataItem.pie[dataObjectName]) {
            // dataTypeName 数据类型名称：source，table，column，file
            // 饼状图默认属性
            const title = {
              text: `${dataTypeList.get(dataTypeName)} ${dataObjectName}`,
              left: 'center'
            }
            const tooltip = {
              trigger: 'item',
              formatter: '{a} <br/>{b} : {c} ({d}%)'
            }
            const barTooltip = {
              trigger: 'axis',
              formatter: '{a} <br/>{b} : {c}'
            }
            //柱状图通用属性
            const barGrid = {
              left: 60,
              right: 20,
              bottom: 35
            }
            const deptMap = dataItem.pie[dataObjectName][dataTypeName].deptMap
            const sysMap = dataItem.pie[dataObjectName][dataTypeName].sysMap
            const templateMap = dataItem.pie[dataObjectName][dataTypeName].templateMap
            // 部门
            if (deptMap) {
              dataItem.pie[dataObjectName][dataTypeName].pieDeptData = {
                title,
                tooltip,
                // legend: {
                //   orient: 'vertical',
                //   left: 'left',
                //   top: 20,
                //   data: Object.keys(deptMap)
                // },
                series: [
                  {
                    name: '部门',
                    type: 'pie',
                    radius: '55%',
                    center: ['50%', '60%'],
                    data: Object.keys(deptMap).map((key) => ({ name: key, value: deptMap[key] }))
                  }
                ]
              }
              dataItem.pie[dataObjectName][dataTypeName].barDeptData = {
                title,
                tooltip: barTooltip,
                grid: barGrid,
                yAxis: {
                  type: 'value'
                },
                axisLabel: {
                  formatter: function (value) {
                    // 每10个字符换一行
                    const maxLength = 10
                    if (value.length > maxLength) {
                      return value.match(new RegExp(`.{1,${maxLength}}`, 'g')).join('\n')
                    }
                    return value
                  }
                },
                xAxis: {
                  type: 'category',
                  data: Object.keys(deptMap),
                  axisTick: {
                    alignWithLabel: true
                  }
                },
                series: [
                  {
                    name: '部门',
                    data: Object.keys(deptMap).map((key) => deptMap[key]),
                    type: 'bar'
                  }
                ]
              }
            }
            // 系统
            if (sysMap) {
              dataItem.pie[dataObjectName][dataTypeName].pieSysData = {
                title,
                tooltip,
                // legend: {
                //   orient: 'vertical',
                //   left: 'left',
                //   top: 20,
                //   data: Object.keys(sysMap)
                // },
                series: [
                  {
                    name: '系统',
                    type: 'pie',
                    radius: '55%',
                    center: ['50%', '60%'],
                    data: Object.keys(sysMap).map((key) => ({ name: key, value: sysMap[key] }))
                  }
                ]
              }
              dataItem.pie[dataObjectName][dataTypeName].barSysData = {
                title,
                tooltip: barTooltip,
                grid: barGrid,
                yAxis: {
                  type: 'value'
                },
                axisLabel: {
                  formatter: function (value) {
                    // 每10个字符换一行
                    const maxLength = 10
                    if (value.length > maxLength) {
                      return value.match(new RegExp(`.{1,${maxLength}}`, 'g')).join('\n')
                    }
                    return value
                  }
                },
                xAxis: {
                  type: 'category',
                  data: Object.keys(sysMap),
                  axisTick: {
                    alignWithLabel: true
                  }
                },
                series: [
                  {
                    name: '系统',
                    data: Object.keys(sysMap).map((key) => sysMap[key]),
                    type: 'bar'
                  }
                ]
              }
            }
            // 数据保护标准
            if (templateMap) {
              dataItem.pie[dataObjectName][dataTypeName].pieTemplateData = {
                title,
                tooltip,
                // legend: {
                //   orient: 'vertical',
                //   left: 'left',
                //   top: 20,
                //   data: Object.keys(templateMap)
                // },
                series: [
                  {
                    name: '数据保护标准',
                    type: 'pie',
                    radius: '55%',
                    center: ['50%', '60%'],
                    data: Object.keys(templateMap).map((key) => ({
                      name: key,
                      value: templateMap[key]
                    }))
                  }
                ]
              }
              dataItem.pie[dataObjectName][dataTypeName].barTemplateData = {
                title,
                tooltip: barTooltip,
                grid: barGrid,
                yAxis: {
                  type: 'value'
                },
                axisLabel: {
                  formatter: function (value) {
                    // 每10个字符换一行
                    const maxLength = 10
                    if (value.length > maxLength) {
                      return value.match(new RegExp(`.{1,${maxLength}}`, 'g')).join('\n')
                    }
                    return value
                  }
                },
                xAxis: {
                  type: 'category',
                  data: Object.keys(templateMap),
                  axisTick: {
                    alignWithLabel: true
                  }
                },
                series: [
                  {
                    name: '数据保护标准',
                    data: Object.keys(templateMap).map((key) => templateMap[key]),
                    type: 'bar'
                  }
                ]
              }
            }
          }
        }
        // Line数据
        for (const dataObjectName in dataItem.lines) {
          // dataObjectName 标准名称
          for (const dataTypeName in dataItem.lines[dataObjectName]) {
            // dataTypeName 数据类型名称：source，table，column，file
            // 默认属性
            const title = {
              text: `${dataTypeList.get(dataTypeName)} ${dataObjectName}`,
              left: 'center'
            }

            const grid = {
              left: 20,
              right: 20,
              bottom: 20,
              top: 80,
              containLabel: true
            }
            const tooltip = {
              trigger: 'axis',
              axisPointer: {
                type: 'cross'
              },
              padding: [5, 10]
            }
            const yAxis = {
              axisTick: {
                show: false
              }
            }
            const deptMap = dataItem.lines[dataObjectName][dataTypeName].deptMap
            const sysMap = dataItem.lines[dataObjectName][dataTypeName].sysMap
            const templateMap = dataItem.lines[dataObjectName][dataTypeName].templateMap
            const times = dataItem.lines[dataObjectName][dataTypeName].times
            // 部门
            if (deptMap) {
              dataItem.list[dataObjectName][dataTypeName].lineDeptData = {
                title,
                grid,
                tooltip,
                yAxis,
                xAxis: {
                  data: times,
                  boundaryGap: false,
                  axisTick: {
                    show: false
                  }
                },
                legend: {
                  data: Object.keys(deptMap),
                  top: 50
                },
                series: Object.keys(deptMap).map((key) => {
                  return {
                    name: key,
                    smooth: true,
                    type: 'line',
                    data: deptMap[key],
                    animationDuration: 500,
                    animationEasing: 'cubicInOut'
                  }
                })
              }
            }
            // 系统
            if (sysMap) {
              dataItem.list[dataObjectName][dataTypeName].lineSysData = {
                title,
                grid,
                tooltip,
                yAxis,
                xAxis: {
                  data: times,
                  boundaryGap: false,
                  axisTick: {
                    show: false
                  }
                },
                legend: {
                  data: Object.keys(sysMap),
                  top: 50
                },
                series: Object.keys(sysMap).map((key) => {
                  return {
                    name: key,
                    smooth: true,
                    type: 'line',
                    data: sysMap[key],
                    animationDuration: 500,
                    animationEasing: 'cubicInOut'
                  }
                })
              }
            }
            // 数据保护标准
            if (templateMap) {
              dataItem.list[dataObjectName][dataTypeName].lineTemplateData = {
                title,
                grid,
                tooltip,
                yAxis,
                xAxis: {
                  data: times,
                  boundaryGap: false,
                  axisTick: {
                    show: false
                  }
                },
                legend: {
                  data: Object.keys(templateMap),
                  top: 50
                },
                series: Object.keys(templateMap).map((key) => {
                  return {
                    name: key,
                    smooth: true,
                    type: 'line',
                    data: templateMap[key],
                    animationDuration: 500,
                    animationEasing: 'cubicInOut'
                  }
                })
              }
            }
          }
        }
      }
    })
    console.log('reportDataList.value', reportDataList.value)
    console.log('menuList.value', menuList.value)

    //用来处理对应的显示对象的操作, 处理数据权限的显示操作
    menuList.value.forEach((menuItem) => {
       if(menuItem.dataObject === "StandardStatistics"){
          //当没有数据权限的数据
          if(!templateList || templateList.value.length <= 0){
            menuItem.show = false
          }
          //要有权限才行
          if(menuItem.show){
              if(!searchValue || !searchValue.value.template){
                menuItem.show = false
              }
          }
          console.log('StandardStatistics menuItem.show', menuItem.show)
       }else if (menuItem.dataObject === "DeptStatistics"){
           //当没有数据权限的数据
          if(!deptList || deptList.value.length <= 0){
            menuItem.show = false
          }
          if(menuItem.show){
              if(!searchValue || !searchValue.value.dept){
                menuItem.show = false
              }
          }
       }else if (menuItem.dataObject === "SystemStatistics"){
          //当没有数据权限的数据
          if(!systemList || systemList.value.length <= 0){
            menuItem.show = false
          }
          if(menuItem.show){
              if(!searchValue || !searchValue.value.sys){
                menuItem.show = false
              }
          }
       }
    })

    console.log('menuList.value2222222', menuList.value)

  } finally {
    loading.close()
  }
}

// 获取总计
function getSum({ row, $index }, menu) {
  if (menu.dataObject == '"StandardStatistics"') {
    return row.total
  }
  if ($index <= 0) {
    return row.total
  }
  return row.total
  // return row.total + (row['sys其他'] || row['dept其他'] || 0)
}

// 数组转化为对象  prefix为前缀
function arrayToObject(array, prefix) {
  return array.reduce((acc, item) => {
    const key = `${prefix}${item.name}`
    acc[key] = item.total
    return acc
  }, {})
}

// 数据标准
const templateList = ref([])
const getTemplateList = async () => {
  const { data } = await dataStandardsPage({ page: 1, pageSize: 999, status: '1' })
  console.log('data', data)
  templateList.value = data
}
// 分类
const classificationList = ref([])
const getClassificationList = async () => {
  const data = await dataClassificationTree()
  classificationList.value = data
}
// 等级
const levelList = ref([])
const getLevelList = async () => {
  const { data } = await levelPage({ page: 1, pageSize: 999 })
  levelList.value = data
}
// 部门
const deptList = ref([])
const getDeptList = async () => {
  const data = await getSimpleDeptList()
  deptList.value = data
}
// 系统
const systemList = ref([])
const getSystemList = async () => {
  const data = await getSimpleSystemList({})
  systemList.value = handleTree(data, 'id', 'pid')
}

const getReportDetail = async () => {
  let data
  console.log('route.name', route.name)
  if (route.name == 'display') {
    data = await reportManageApi.reportManageGetShow()
  } else if (route.name == 'Index') {
    data = await reportManageApi.reportManageGetHome()
  } else if (route.query.id || props.reportId) {
    data = await reportManageApi.reportManageGet({ id: route.query.id || props.reportId })
  } else {
    return
  }

  defaultQuery.value = JSON.parse(data?.defaultQuery)
  defaultQuery.value.defaultTime = data?.defaultTime
  if (!searchValue.value.defaultTime) {
    searchValue.value = defaultQuery.value
  }
  // 报表数据
  getReportData()
}

onMounted(() => {
  getTemplateList()
  getClassificationList()
  getLevelList()
  getDeptList()
  getSystemList()
  // 获取默认query
  getReportDetail()
})
</script>
<style lang="scss">
.item {
  background: red;
}
.chart-list {
  display: flex;
  flex-wrap: wrap;
}
.Table-css {
  width: 100%;
  margin-bottom: 12px;
  // height: 100px;
  // background-color: red;
}
.Pie-css {
  width: 50%;
  margin-bottom: 12px;
  height: 350px;
  // background-color: blue;
}
.Bar-css {
  width: 50%;
  margin-bottom: 12px;
  height: 350px;
  // background-color: green;
}
.Line-css {
  width: 50%;
  margin-bottom: 12px;
  height: 350px;
  // background-color: green;
}
</style>
